package com.cdn.allmobilestore.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.cdn.allmobilestore.ulti.Constant;

import android.util.Log;


public class BaseService {
	private static final String TAG = "BaseService";
	private static int K_URL_MIN_LENGTH = 3;
	private static int K_BUFFER_SIZE = 2 * 1024;

	public static final int TEXT_MAX = 140;

	public static final int TEXT_EMPTY = 1;
	public static final int TEXT_OVER140 = 2;
	public static final int TEXT_IN140 = 0;

	public static final int HTTP_TIMEOUT = 30000;

  /**
   * Get our single instance of our HttpClient object.
   *
   * @return an HttpClient object with connection parameters set
   */
 
	
  public static String downLoadUrlInBuffer(String url, int timeout){
      BufferedReader in = null;
      
      try {
          HttpClient client = getHttpClient();
          HttpGet request = new HttpGet();
          request.setURI(new URI(url));
         
          HttpResponse response = client.execute(request);
          for(Header h : response.getAllHeaders())
          {
              Log.d(h.getName(),  h.getValue());
          }
          
          StringBuffer sb = new StringBuffer("");
          if(response.getEntity() != null) {
              in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
             
              String line = "";
              while ((line = in.readLine()) != null) {
                  sb.append(line);
              }
              in.close();
          } else {
              return null;
          }
          String result = sb.toString();
          Log.i(TAG, "result:" + result);
          return result;
      } catch (Exception e) {
          e.printStackTrace();
      } 
      finally {
          if (in != null) {
              try {
                  in.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      
      return null;
  }
  
//	public static String downLoadUrlInBuffer(final String url, int timeout) {
//		Log.d(TAG, "downLoadUrlInBuffer()");
//		Log.i(TAG, "URL:" + url);
//
//		String rs = "";
//		final StringBuffer sb = new StringBuffer();
//		try {
//			final URLConnection cn = new URL(url).openConnection();
//			cn.setReadTimeout(timeout);
//			cn.connect();
//			final InputStream stream = cn.getInputStream();
//			final byte[] buf = new byte[Constants.BUFFER_SIZE];
//			do {
//				final int numread = stream.read(buf);
//				if (numread <= 0) {
//					// Nothing left to read so quit
//					break;
//				} else {
//					final String s = new String(buf, 0, numread);
//					sb.append(s);
//				}
//			} while (true);
//			rs = sb.toString();
//		} catch (final Exception e) {
//			e.printStackTrace();
//		}
//
//		Log.i(TAG, "result:" + rs);
//		return rs;
//	}

	public static String downLoadUrlInBuffer(final String url) {
		Log.d(TAG, "downLoadUrlInBuffer()");
		Log.i(TAG, "URL:" + url);

		String rs = "";
		final StringBuffer sb = new StringBuffer();
		try {
			final URLConnection cn = new URL(url).openConnection();
			cn.connect();
			final InputStream stream = cn.getInputStream();
			final byte[] buf = new byte[Constant.BUFFER_SIZE];
			do {
				final int numread = stream.read(buf);
				if (numread <= 0) {
					// Nothing left to read so quit
					break;
				} else {
					final String s = new String(buf, 0, numread);
					sb.append(s);
				}
			} while (true);
			rs = sb.toString();
		} catch (final Exception e) {
			e.printStackTrace();
		}

		Log.i(TAG, "result:" + rs);
		return rs;
	}

	public static boolean downloadFile(final String dataPath, final String url,
			final boolean useOverWrite) {
		if (url == null) {
			return false;
		}
		if (url.length() < K_URL_MIN_LENGTH) {
			return true;
		}
		final String path = dataPath;
		final File file = new File(path);
		try {
			if (file.exists()) {
				if (!useOverWrite) {
					return false;
				}
				file.delete();
				file.createNewFile();
			} else {
				makeDir(path);
				file.createNewFile();
			}
			final FileOutputStream out = new FileOutputStream(path);
			final URLConnection cn = new URL(url).openConnection();
			cn.connect();
			final InputStream stream = cn.getInputStream();
			final byte[] buf = new byte[K_BUFFER_SIZE];
			do {
				final int numread = stream.read(buf);
				if (numread <= 0) {
					// Nothing left to read so quit
					break;
				} else {
					out.write(buf, 0, numread);
					out.flush();
				}
			} while (true);
			out.close();
		} catch (final Exception e) {
			e.printStackTrace();
			return true;
		}
		return false;
	}

	public static void makeDir(final String root) {
		try {
			final File file = new File(root);
			final File parent = new File(file.getParent());
			parent.mkdirs();
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean checkEmail(String inputMail) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+");
		return pattern.matcher(inputMail).matches();
	}

	public static HttpClient getHttpClient() {
		HttpClient mHttpClient = new DefaultHttpClient();
		ClientConnectionManager mgr = mHttpClient.getConnectionManager();
		final HttpParams params = mHttpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
		ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
		ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
		ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
		ConnManagerParams.setMaxTotalConnections(params, 40);

		mHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(
				params, mgr.getSchemeRegistry()), params);

		return mHttpClient;
	}
}
